const fs = require('fs');
const path = require('path');

// 递归查找所有 JavaScript 文件
function findJsFiles(dir) {
  const files = [];
  const items = fs.readdirSync(dir);
  
  for (const item of items) {
    const fullPath = path.join(dir, item);
    const stat = fs.statSync(fullPath);
    
    if (stat.isDirectory()) {
      // 跳过 node_modules 和 static 目录
      if (item === 'node_modules' || item === 'static') {
        continue;
      }
      files.push(...findJsFiles(fullPath));
    } else if (item.endsWith('.js') || item.endsWith('.jsx')) {
      files.push(fullPath);
    }
  }
  
  return files;
}

// 替换文件中的 .scss 引用
function replaceScssImports(filePath) {
  try {
    console.log(`Processing: ${filePath}`);
    
    // 读取文件内容
    let content = fs.readFileSync(filePath, 'utf8');
    let modified = false;
    
    // 替换 import 语句中的 .scss 为 .css
    const importRegex = /import\s+['"]([^'"]*\.scss)['"]/g;
    content = content.replace(importRegex, (match, importPath) => {
      const newPath = importPath.replace('.scss', '.css');
      console.log(`  Replacing: ${importPath} -> ${newPath}`);
      modified = true;
      return `import '${newPath}'`;
    });
    
    // 替换 require 语句中的 .scss 为 .css
    const requireRegex = /require\s*\(\s*['"]([^'"]*\.scss)['"]\s*\)/g;
    content = content.replace(requireRegex, (match, requirePath) => {
      const newPath = requirePath.replace('.scss', '.css');
      console.log(`  Replacing: ${requirePath} -> ${newPath}`);
      modified = true;
      return `require('${newPath}')`;
    });
    
    // 如果有修改，写回文件
    if (modified) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`  ✅ Updated: ${filePath}`);
    }
    
    return modified;
  } catch (error) {
    console.error(`  ❌ Error processing ${filePath}:`, error.message);
    return false;
  }
}

// 主函数
function main() {
  console.log('Starting SCSS import replacement...\n');
  
  const jsFiles = findJsFiles('.');
  console.log(`Found ${jsFiles.length} JavaScript files to process.\n`);
  
  let updatedCount = 0;
  
  for (const file of jsFiles) {
    if (replaceScssImports(file)) {
      updatedCount++;
    }
  }
  
  console.log(`\n✅ Completed! Updated ${updatedCount} files.`);
}

main(); 